/**
 * 不需要登录即可使用的路由
 */
import { Router } from "express";
import svgCaptcha from "svg-captcha";
import dayjs from "dayjs";

import db from "../database.js";
import {
  checkPassword,
  makePassword,
  orderBy,
  splitNumUnits,
} from "../utils.js";

import { validate } from "../middlewares.js";
import validators from "../validate.js";
import multiAvatar from "@multiavatar/multiavatar";
import { signJWT } from "../jwt.js";

// 实例化路由对象
const router = Router();

const [expires, units] = splitNumUnits(process.env.expiresIn ?? "24h");

// 生成随机头像
// router.get("/avatar/:id.svg", (req, res) => {
//   res.type("image/svg+xml");
//   res.send(multiAvatar(req.params.id));
// });

// 权限管理路由
const permissionRouter = {
  path: "/permission",
  meta: {
    title: "权限管理111",
    icon: "lollipop",
    rank: 10,
  },
  children: [
    {
      path: "/permission/page/index",
      name: "PermissionPage",
      meta: {
        title: "页面权限111",
        // roles: ["admin", "common"],
        // roles: [],
        showParent: true,
      },
    },
    {
      path: "/permission/button/index",
      name: "PermissionButton",
      meta: {
        title: "按钮权限1111",
        // roles: ["admin", "common"],
        // roles: [],
        auths: ["btn_add", "btn_edit"],
        showParent: true,
      },
    },
  ],
};

// 行政部门员工的公文管理模块路由
const administration_document_router = {
  path: "/public_admin_module",
  meta: {
    icon: "bi:briefcase-fill",
    title: "公文管理模块",
    rank: 2,
  },
  children: [
    {
      path: "/public_admin_module/maintenance",
      name: "maintenance",
      meta: {
        title: "公文维护",
        showParent: true,
      },
    },
  ],
};

// 管理层的公文管理模块路由
const management_document_router = {
  path: "/public_admin_module",
  meta: {
    icon: "bi:briefcase-fill",
    title: "公文管理模块",
    rank: 2,
  },
  children: [
    {
      path: "/public_admin_module/approval",
      name: "approval",
      meta: {
        title: "公文审批",
        showParent: true,
      },
    },
  ],
};

// 行政部门的公共信息模块路由
const administration_information_router = {
  path: "/public_information_module",
  meta: {
    icon: "mingcute:message-3-line",
    title: "公共信息模块",
    rank: 3,
  },
  children: [
    {
      path: "/public_information_module/Information",
      name: "Information",
      meta: {
        title: "公共信息模块",
        auths: ["btn_add"],
        showParent: true,
      },
    },
  ],
};

// 其他部门的公共信息模块路由
const other_information_router = {
  path: "/public_information_module",
  meta: {
    icon: "mingcute:message-3-line",
    title: "公共信息模块",
    rank: 3,
  },
  children: [
    {
      path: "/public_information_module/Information",
      name: "Information",
      meta: {
        title: "公共信息模块",
        showParent: true,
      },
    },
  ],
};

// 管理层的行政办公模块路由
const management_office_router = {
  path: "/executive_office_module",
  meta: {
    icon: "streamline:politics-speech",
    title: "行政办公模块",
    rank: 4,
  },
  children: [
    {
      path: "/executive_office_module/meeting",
      name: "meeting",
      meta: {
        title: "会议管理",
      },
    },
    {
      path: "/executive_office_module/supplies",
      name: "supplies",
      meta: {
        title: "用品管理",
      },
    },
    {
      path: "/executive_office_module/vehicle",
      name: "vehicle",
      meta: {
        title: "车辆管理",
      },
    },
    {
      path: "/executive_office_module/book",
      name: "book",
      meta: {
        title: "图书管理",
      },
    },
    // {
    //   path: "/executive_office_module/asset",
    //   name: "asset",
    //   meta: {
    //     title: "资产管理",
    //   },
    // },
  ],
};

// 行政部门的行政办公模块路由
const administration_office_router = {
  path: "/executive_office_module",
  meta: {
    icon: "streamline:politics-speech",
    title: "行政办公模块",
    rank: 4,
  },
  children: [
    {
      path: "/executive_office_module/meeting",
      name: "meeting",
      meta: {
        title: "会议管理",
        auths: ["btn_approval"],
      },
    },
    {
      path: "/executive_office_module/supplies",
      name: "supplies",
      meta: {
        title: "用品管理",
        auths: ["btn_approval"],
      },
    },
    {
      path: "/executive_office_module/vehicle",
      name: "vehicle",
      meta: {
        title: "车辆管理",
        auths: ["btn_approval"],
      },
    },
    {
      path: "/executive_office_module/book",
      name: "book",
      meta: {
        title: "图书管理",
        auths: ["btn_approval"],
      },
    },
    // {
    //   path: "/executive_office_module/asset",
    //   name: "asset",
    //   meta: {
    //     title: "资产管理",
    //     auths: ["btn_approval"],
    //   },
    // },
  ],
};

// 其他部门的行政办公模块路由
const other_office_router = {
  path: "/executive_office_module",
  meta: {
    icon: "streamline:politics-speech",
    title: "行政办公模块",
    rank: 4,
  },
  children: [
    {
      path: "/executive_office_module/meeting",
      name: "meeting",
      meta: {
        title: "会议管理",
      },
    },
    {
      path: "/executive_office_module/supplies",
      name: "supplies",
      meta: {
        title: "用品管理",
      },
    },
    {
      path: "/executive_office_module/vehicle",
      name: "vehicle",
      meta: {
        title: "车辆管理",
      },
    },
    {
      path: "/executive_office_module/book",
      name: "book",
      meta: {
        title: "图书管理",
      },
    },
  ],
};

// 权限管理模块路由 (只有系统管理员可见)
const permission_management_router = {
  path: "/permission_management_module",
  redirect: "/permission_management_module/persona",
  meta: {
    icon: "carbon:id-management",
    title: "权限管理模块",
    rank: 8,
  },
  children: [
    {
      path: "/permission_management_module/persona",
      name: "persona",
      meta: {
        title: "角色管理",
      },
    },
    {
      path: "/permission_management_module/user",
      name: "user",
      meta: {
        title: "用户管理",
      },
    },
  ],
};

// 系统管理员的系统管理模块路由
const system_management_router = {
  path: "/system_management_module",
  redirect: "/system_management_module",
  meta: {
    icon: "tdesign:system-setting",
    title: "系统管理模块",
    rank: 9,
  },
  children: [
    {
      path: "/system_management_module/password",
      name: "password",
      meta: {
        title: "密码修改",
      },
    },
    {
      path: "/system_management_module/module",
      name: "module",
      meta: {
        title: "模块管理",
      },
    },
    {
      path: "/system_management_module/code",
      name: "code",
      meta: {
        title: "代码定义",
      },
    },
    {
      path: "/system_management_module/system",
      name: "system",
      meta: {
        title: "系统初始化",
      },
    },
  ],
};

// 其他部门的系统管理模块路由
const other_system_management_router = {
  path: "/system_management_module",
  redirect: "/system_management_module",
  meta: {
    icon: "tdesign:system-setting",
    title: "系统管理模块",
    rank: 9,
  },
  children: [
    {
      path: "/system_management_module/password",
      name: "password",
      meta: {
        title: "密码修改",
        showParent: true,
      },
    },
  ],
};

// 人事部门的人事档案模块路由
const personnel_file_router = {
  path: "/personnel_file_module",
  redirect: "/personnel_file_module/resume",
  meta: {
    icon: "vaadin:records",
    title: "人事档案模块",
    rank: 10,
  },
  children: [
    {
      path: "/personnel_file_module/resume",
      name: "resume",
      meta: {
        title: "人员履历",
      },
    },
    {
      path: "/personnel_file_module/dimission",
      name: "dimission",
      meta: {
        title: "离职申请",
      },
    },
    {
      path: "/personnel_file_module/attendance",
      name: "attendance",
      meta: {
        title: "员工考勤",
        auths: ["btn_view"],
      },
    },
  ],
};

// 管理层的人事档案模块路由
const management_personnel_file_router = {
  path: "/personnel_file_module",
  redirect: "/personnel_file_module/resume",
  meta: {
    icon: "vaadin:records",
    title: "人事档案模块",
    rank: 10,
  },
  children: [
    {
      path: "/personnel_file_module/dimission",
      name: "dimission",
      meta: {
        title: "离职申请",
        auths: ["btn_approval"],
      },
    },
    {
      path: "/personnel_file_module/attendance",
      name: "attendance",
      meta: {
        title: "员工考勤",
      },
    },
    {
      path: "/personnel_file_module/positiveApply",
      name: "positiveApply",
      meta: {
        title: "审核转正申请",
      },
    },
    {
      path: "/personnel_file_module/retireApply",
      name: "retireApply",
      meta: {
        title: "审核离职申请",
      },
    },
  ],
};

// 其他部门的人事档案模块路由
const other_personnel_file_router = {
  path: "/personnel_file_module",
  redirect: "/personnel_file_module/resume",
  meta: {
    icon: "vaadin:records",
    title: "人事档案模块",
    rank: 10,
  },
  children: [
    {
      path: "/personnel_file_module/dimission",
      name: "dimission",
      meta: {
        title: "离职申请",
      },
    },
    {
      path: "/personnel_file_module/attendance",
      name: "attendance",
      meta: {
        title: "员工考勤",
      },
    },
  ],
};

// 转正申请的路由
const regularization_router = {
  path: "/personnel_file_module/regularization",
  name: "regularization",
  meta: {
    title: "转正申请",
    auths: ["btn_approval"],
  },
};

// 后端动态返回路由
router.get("/getAsyncRoutes", async (req, res) => {
  return res.send({
    success: true,
    message: "获取动态路由成功",
    data: finally_router,
  });
});

// 最终确定返回的路由
let finally_router = [];

/**
 * 根据传入的部门，返回路由
 * @param {string} org
 * @returns {Array}
 */
const get_finally_router = (org) => {
  let _router = [];
  if (org.includes("行政部门")) {
    _router = [
      administration_document_router,
      administration_information_router,
      administration_office_router,
      other_system_management_router,
      other_personnel_file_router,
    ];
  } else if (org.includes("管理层")) {
    _router = [
      management_document_router,
      other_information_router,
      management_office_router,
      other_system_management_router,
      management_personnel_file_router,
    ];
  } else if (org.includes("系统管理员")) {
    _router = [
      other_information_router,
      other_office_router,
      permission_management_router,
      system_management_router,
      other_personnel_file_router,
    ];
  } else if (org.includes("人事部门")) {
    _router = [
      other_information_router,
      other_office_router,
      other_system_management_router,
      personnel_file_router,
    ];
  } else {
    console.log("其他部门");
    _router = [
      other_information_router,
      other_office_router,
      other_system_management_router,
      other_personnel_file_router,
    ];
  }
  return _router;
};

// 用户登录
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user =
    await db.findOne`SELECT * FROM Person WHERE username = ${username}`;
  if (user?.demission == "是") {
    return res.send({
      success: false,
      message: "该账号已离职!",
    });
  }
  if (user && checkPassword(password, user.password)) {
    // 将用户 id 写入 session
    req.session.userId = user.id;
    // 查看当前登录用户是否拥有通信录
    const existContact =
      await db.findOne`SELECT * FROM Contacts WHERE personId = ${user.id}`;
    if (!existContact) {
      // 如果没有则创建一个
      await db.run`INSERT INTO Contacts (personId) VALUES (${user.id})`;
    }
    // 判断当前登录用户部门
    finally_router = get_finally_router(user.org.toString());

    // 判断当前用户是否转正
    if (user.formal == "否") {
      finally_router.forEach((item) => {
        if (item.path == "/personnel_file_module") {
          if (item.children.includes(regularization_router)) {
            return;
          }
          item.children.unshift(regularization_router);
        }
      });
    }
    return res.send({
      success: true,
      message: "登录成功!",
      data: {
        ...user,
        accessToken: await signJWT({ userId: user.id }),
        expires: dayjs().add(expires, units).format("YYYY-MM-DD HH:mm:ss"),
      },
    });
  }
  console.log("登录失败");
  res.send({
    success: false,
    message: "账号或密码错误!",
  });
});

export default (app) => {
  app.use("/api", router);
  // app.get("/captcha", captcha);
};
